/*
 * @Author: 魏进 3413105907@qq.com
 * @Date: 2025-03-21 11:34:58
 * @LastEditors: 魏进 3413105907@qq.com
 * @LastEditTime: 2025-03-21 20:07:52
 * @FilePath: \client\js\chat.js
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
 */

window.onload = function () {


    var vm = new Vue({
        el: "#chat-app",
        data: {
            currentUser: '',
            //用于websocket建立连接
            ws: null,
            records: [],
            ranks: [],
            users:[],
            message: '',
            //判断websocket是否建立连接
            isConnect: false,
            baseurl: 'http://localhost:9090'
        },
        created() {
            //获取登录用户名
            const urlParams = new URLSearchParams(window.location.search);
            //当前登录用户
            this.currentUser = urlParams.get('user')
            const wsUrl = `ws://localhost:9090/chat?username=${this.currentUser}`
            this.ws = new WebSocket(wsUrl)
            //初始化websocket其他方法
            this.initWebsocket();
            //获取聊天记录
            this.getChatCrods()
            //使用定时任务建立重连机制
            const self = this
            setInterval(function () {
                if (!self.isConnect){
                    self.ws = new WebSocket(wsUrl)
                    self.isConnect = true
                }
            },5000)
        },
        updated() {
            this.scrollToBottom()
        },
        methods: {
            // 初始化websocket
            initWebsocket() {
                const self = this
                //收到信息
                self.ws.onmessage = (event) => {
                    //第一遍解析为字符串，第二遍解析为JSON
                    var res = JSON.parse(event.data)
                    //如果是字符串接着转换一次
                    if (typeof res === 'string') {
                        res = JSON.parse(res)
                    }
                    if (res.status === 2000) {
                        //收到信息，添加到数组中渲染
                        self.records.push(res.data)
                    } else if (res.status === 2001) {
                        //排行榜
                        self.ranks = res.data
                    } else if (res.status === 2002){
                        self.users = res.data
                    } else if (res.status === -1) {
                        alert(res.message)
                    }
                }
                //建立连接
                self.ws.onopen = (event) => {
                    self.isConnect = true
                }
                //关闭连接
                self.ws.onclose = (event)=>{
                    self.isConnect = false
                }
                //发生错误
                self.ws.onerror = (event)=>{
                    self.isConnect = false
                    console.log('websocket 发生异常：',event)
                }
            },
            //获取聊天记录
            getChatCrods() {
                axios
                    .get(this.baseurl + `/chatHistory/page`, {
                        params: {
                            pageNumber: 1,
                            pageSize: 300
                        }
                    })
                    .then(res => {
                        if (res.data.status === 0) {
                            this.records = res.data.data.records;
                        } else {
                            alert(res.data.message);
                        }
                    })
                    .catch((error) => {
                        alert(error.message);
                        console.log(error);
                    });
            },
            //发送消息
            sendMessage() {
                if (!this.message) {
                    alert('请先输入你要发送的信息')
                    return
                }
                const msgObj = {
                    sender: this.currentUser,
                    content: this.message
                }
                const jsonMsg = JSON.stringify(msgObj)
                this.ws.send(jsonMsg);
                this.message = ''
            },
            //使滚动条滚动到最下面
            scrollToBottom() {
                this.$nextTick(() => {
                    var chatContainer = this.$el.querySelector('#content');
                    if (chatContainer) {
                        chatContainer.scrollTop = chatContainer.scrollHeight;
                    }
                });
            },
        }
    });
    Vue.filter("dateTimeFormat", function (dateTime) {
        var y = dateTime.substring(0, 4);

        var M = dateTime.substring(5, 7);
        var d = dateTime.substring(8, 10);
        var H = (dateTime.substring(11, 13));
        var m = (dateTime.substring(14, 16));
        // var s = (dateTime.getSeconds() + "").padStart(2,"0");

        //ES6以后 可以使用``拼接字符串 变量使用${}
        return `${y}-${M}-${d} ${H}:${m}`;
        // return `${y}-${M}-${d} ${H}:${m}:${s}`;
    })


}